package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.Resource;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.mapper.UserSafeMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserSafeMapper userMapper;
    //此处如此使用因为不同模块下有同名的UserMapper，则需要改名
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private SecurityConfigProperties securityConfigProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /*
     * 用户登录
     */
    @Override
    public UserVo login(LoginDto loginDto) {
        //1.根据用户名查询用户
        User user = userMapper.selectByUserName(loginDto.getUsername());

        //2.判断用户是否为空
        if (ObjectUtil.isEmpty(user)) {
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        //3.判断用户是否被禁用
        if (user.getDataState().equals(SuperConstant.DATA_STATE_1)) {
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }

        //4.判断密码是否正确
        if (BCrypt.checkpw(loginDto.getPassword(), user.getPassword())) {
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }

        //对象转换
        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        //5.密码脱敏
        userVo.setPassword(null);
        //获取资源列表
        List<Resource> resourceList = resourceMapper.selectListByUserId(user.getId());
        //获取资源列表requestPath
        List<String> urlList = resourceList.stream().map(Resource::getRequestPath).collect(Collectors.toList());
        //获取白名单列表
        List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
        urlList.addAll(publicAccessUrls);

        //6.根据用生成JWT
        Map map=new HashMap();
        map.put("currentUser", JSONUtil.toJsonStr(userVo));
        String token= JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), map);

        //将redis中信息时间设置与token有效期一样长
        int ttl=jwtTokenManagerProperties.getTtl() / 1000;
        //将可访问的资源路径存入Redis
        redisTemplate.opsForValue().set(CacheConstant.PUBLIC_ACCESS_URLS+user.getId(),JSONUtil.toJsonStr(urlList),ttl, TimeUnit.SECONDS);


        userVo.setUserToken(token);
        return userVo;
    }
}
